package com.aier.controller.report;

import com.aier.aop.FreezeRowColHandler;
import com.aier.bean.common.CommonResult;
import com.aier.bean.report.BuildsPosition;
import com.aier.service.report.BuildsPositionService;
import com.alibaba.excel.EasyExcel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * 建仓报表controller
 */
@Controller
@CrossOrigin
@RequestMapping("/report")
public class BuildsPositionController {

    @Autowired
    private BuildsPositionService buildsPositionService;

    @ResponseBody
    @RequestMapping("/get_build_position")
    public CommonResult buildBuildsPosition(){
        List<BuildsPosition> buildsPositionList = buildsPositionService.buildBuildsPosition();
        return CommonResult.success(buildsPositionList);
    }

    @ResponseBody
    @RequestMapping("/download_build_position")
    public void downloadBuildsPosition(HttpServletResponse response) throws IOException {
        // 1. 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("建仓表", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        // 2. 创建空数据列表
        List<BuildsPosition> buildsPositionList = buildsPositionService.buildBuildsPosition();

        // 3. 使用EasyExcel写入模板
        EasyExcel.write(response.getOutputStream(), BuildsPosition.class)
                .sheet("建仓数据")
                .registerWriteHandler(new FreezeRowColHandler(0,1,0,1))
                .doWrite(buildsPositionList);
    }
}
